package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"hema-fresh/hemarpc/hemarpc"
	"hema-fresh/hemarpc/internal/svc"
	"hema-fresh/model/cache"
	"hema-fresh/model/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopListLogic {
	return &ShopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopListLogic) ShopList(in *hemarpc.ShopListRequest) (*hemarpc.ShopListResponse, error) {
	// todo: add your logic here and delete this line

	var shops mysql.Shop

	key := fmt.Sprintf("ShopList_%s", in)

	result, _ := cache.Rdb.Get(cache.Ctx, key).Result()

	var list []*hemarpc.ShopList
	if result == "" {
		var err error
		list, err = shops.ShopList(mysql.DB, list, in)
		if err != nil {
			return nil, err
		}

		marshal, _ := json.Marshal(list)

		cache.Rdb.Set(cache.Ctx, key, marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	return &hemarpc.ShopListResponse{
		List: list,
	}, nil
}
